package com.jsits.v2x.common.connection.socket;

import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.Date;

public abstract class SocketServer extends SocketBase
{
	/*
	 * 日志
	 */
	private static Logger logger = LoggerFactory.getLogger(SocketServer.class);
	
	/*
	 * mina客户端与服务端建立的连接信息
	 */
	private SocketAcceptor acceptor;
	
	/*
	 * 最大缓冲区长度
	 */
	public static final int MAX_BUFFER_SIZE = 1024 * 1024;
	
	/**
	 * 建立服务端
	 * @see SocketBase#connectServer()
	 *  0.连接成功 1.拒绝连接 2.连接失败
	 */
	protected Integer connectServer()
	{
		Integer retValue = 0;
		
		try {
			acceptor = new NioSocketAcceptor();
			//设置消息的编解码
			SocketFactory factory = new SocketFactory();
			factory.setSocketBase(this);
			acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(factory));
			//设置消息
			MessageHandler messageHandle = new MessageHandler();
			messageHandle.setSocketBase(this);
			acceptor.setHandler(messageHandle);
			//设置客户端连接属性
			acceptor.getSessionConfig().setUseReadOperation(true);
			acceptor.getSessionConfig().setMaxReadBufferSize(MAX_BUFFER_SIZE);
			
			//与服务端建立连接
			acceptor.bind(new InetSocketAddress(serverInfo.getPort()));
			
			logger.info("Create socket server success, port: " + serverInfo.getPort());
			
			serverInfo.setStatus(true);
			serverInfo.setTimeStamp(new Date().getTime());
			
		}catch (Exception e) {
			logger.error("Create socket server failed, port: " + serverInfo.getPort());
			retValue = 2;
		}
		
		return retValue;
	}
	
	/*
	 * 断开服务端连接
	 * @see SocketBase#disConnectServer()
	 */
	protected CloseFuture disConnectServer()
	{
		acceptor.dispose();
		return null;
	}

	/*
	 * 发送消息至客户端
	 * @see SocketBase#sendMessage(SocketMessage, org.apache.mina.core.session.IoSession)
	 */
	public void sendMessage(SocketMessage message, IoSession session) 
	{
		//将消息写入Session，在MessageEncoder中会对消息进行编码并发送至服务端
		session.write(message);
	}

}
